package com.lw.extraceim.ui.fragments;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.Nullable;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lw.extraceim.R;
import com.lw.extraceim.app.ExtraceApplication;
import com.lw.extraceim.loader.PackageLoader;
import com.lw.extraceim.model.TransPackage;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.tp.PackageInfoActivity;
import com.lw.extraceim.ui.adapter.TransPackageAdapter;
import com.lw.extraceim.ui.fragments.base.BaseFragment;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.zxing.ExtraceCaptureActivity;

import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description : 我的转运
 * @Date : 2019/5/13 21:07
 */
public class MyTransFragment extends TaskFragment {
    private static final String TAG = "MyTransFragment";

    private Button mButtonTransport;
    private ListView mTransportPackageList;
    private TransPackageAdapter adapter;

    private List<TransPackage> transPackageList;
    PackageLoader loader;

    public MyTransFragment(Context mContext, ExtraceApplication application) {
        super(mContext, application);
    }

    @Override
    public View initView() {
        View view = View.inflate(mContext, R.layout.layout_my_trans_fragment, null);
        mButtonTransport = view.findViewById(R.id.transport_button);
        mTransportPackageList = view.findViewById(R.id.transporting_package_list);
        return view;
    }

    @Override
    public void initData() {
        loader = new PackageLoader(getContext());
        loadTransortingPackage();
    }

    @Override
    public void initEvent() {
        mButtonTransport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentIntegrator intentIntegrator = new IntentIntegrator(getActivity());
                intentIntegrator.setCaptureActivity(ExtraceCaptureActivity.class);
                intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
                intentIntegrator.setPrompt("扫描条形码");
                //设置请求码
                intentIntegrator.setRequestCode(ExtraceCaptureActivity.SCAN_TRANSPORT_PACKAGE);
                application.setScanActivityRequestCode(ExtraceCaptureActivity.SCAN_TRANSPORT_PACKAGE);

                intentIntegrator.setBeepEnabled(true);
                intentIntegrator.setBarcodeImageEnabled(true);
                intentIntegrator.initiateScan();
            }
        });
        mTransportPackageList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TransPackage transPackage = transPackageList.get(position);
                PackageInfoActivity.actionStart(getContext(),transPackage);
            }
        });

    }

    @Override
    public void refreshUI() {
        refreshTransPackageList();
    }

    public void refreshTransPackageList() {
        mTransportPackageList.setAdapter(new TransPackageAdapter(transPackageList, getContext()));
    }

    public void loadTransortingPackage() {
        loader.getTransportintPackage(application.getUserInfo().getuId(), new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                Log.d(TAG, "onResponse: " + response.reseponseJson);
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    try {
                        transPackageList = JsonUtils.fromJson(response.reseponseJson.getJSONArray("packageList").toString(), new TypeToken<List<TransPackage>>() {
                        });
                        for(TransPackage transPackage : transPackageList){
                            transPackage.onLoad();
                        }
                        refreshTransPackageList();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }

    /**
     * 转运包裹
     *
     * @param userId
     * @param packageId
     */
    public void transport(Integer userId, final String packageId) {
        loader.transportPackage(packageId, userId, new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                Log.d(TAG, "onResponse: " + response.reseponseJson);
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    alert("已添加到转运列表中");
                } else {
                    alert(response.code.getMessage());
                }
            }
        });

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ExtraceCaptureActivity.SCAN_TRANSPORT_PACKAGE: {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data);
                if (scanResult != null) {
                    String packageId = scanResult.getContents();
                    if (packageId != null) {
                        Log.d(TAG, "onActivityResult: 开始转运" + packageId);
                        transport(application.getUserInfo().getuId(), packageId);
                    } else {
                        toast("扫描错误");
                    }
                } else {
                    toast("扫描错误");
                }
            }
        }
    }

    @Override
    public void onResume() {
        Log.d(TAG, "onResume: 执行O");
        loadTransortingPackage();
        super.onResume();
    }
}
